package com.zhuannimei.ui;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.util.LogUtils;
import com.zhuannimei.GlobalApplication;
import com.zhuannimei.R;
import com.zhuannimei.adapter.BuyHistoryAdapter;
import com.zhuannimei.adapter.HistoryOneGouAdapter;
import com.zhuannimei.adapter.ProductHistoryAdapter;
import com.zhuannimei.domain.HistoryOneShop;
import com.zhuannimei.domain.ProductHistory;
import com.zhuannimei.net.RequestServerData;
import com.zhuannimei.parser.HistoryOneShopParser;
import com.zhuannimei.parser.ProductHistoryParser;
import com.zhuannimei.service.AsyncDataLoader;
import com.zhuannimei.service.AsyncDataLoader.Callback;
import com.zhuannimei.utility.WuLog;
import com.zhuannimei.utility.ZnmData;
import com.zhuannimei.utility.ZnmHttpParams;
import com.zhuannimei.view.ZnmRefreshListView;
import com.zhuannimei.view.ZnmRefreshListView.OnCancelListener;
import com.zhuannimei.view.ZnmRefreshListView.OnRefreshListener;

/**
 * 购买记录
 * 
 * @author Jack 2014-3-5
 * 
 * 
 */
public class BuyHistoryActivity extends BaseActivity {

	private static final String TAG = "BuyHistoryActivity";
	private HistoryOneGouAdapter mSecAdapter;
	private ProductHistoryAdapter mFirstAdapter;

	private ZnmRefreshListView duihuan_ZR;
	private ZnmRefreshListView oneyuan_ZR;
	private TextView buy_duihuan_tv;
	private TextView buy_one_tv;
	private List<HistoryOneShop> mSecList = new ArrayList<HistoryOneShop>();
	private List<ProductHistory> mFirstList = new ArrayList<ProductHistory>();
	private boolean mPlush = false;

	private LinearLayout mFiestLL;

	private LinearLayout mSecLL;

	// private ViewFlipper vf;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.buy_history);
		initView();
		// 设置数据
		setListener();
		setData();
	}

	/**
	 * 
	 */
	private void getBuyHistory() {
		RequestParams mParams = ZnmHttpParams.getDefaultRequestParams();
		mParams.addBodyParameter("pageIndex", "0");
		mParams.addBodyParameter("userId", ZnmData.getUserData()
				.getUserUserId());
		RequestServerData.getProductHistory(mParams,
				new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						WuLog.i(TAG, "" + responseInfo.result);
						try {
							JSONObject jo = new JSONObject(responseInfo.result);
							if ("0".equals(jo.optString("code"))) {
								List<ProductHistory> list = new ProductHistoryParser()
										.parseJSON(responseInfo.result);
								if (list != null && list.size() != 0) {
									mFirstList.clear();
									mFirstList.addAll(list);
								}
								mFirstAdapter.notifyDataSetChanged();
								// 先删后存
								GlobalApplication.appDB.deleteByWhere(
										ProductHistory.class, null);
								for (ProductHistory pu : mFirstList) {
									GlobalApplication.appDB.save(pu);
								}
							}
							duihuan_ZR.onRefreshComplete();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						showCustomToast("网络不给力" + error.getExceptionCode());
					}
				});
	}

	private void getOneBuyHistory() {
		RequestParams mParams = ZnmHttpParams.getDefaultRequestParams();
		mParams.addBodyParameter("userId", ""
				+ ZnmData.getUserData().getUserUserId());
		mParams.addBodyParameter("pageIndex", "0");
		RequestServerData.getLuckHistory(mParams,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						WuLog.i(TAG, "成功" + responseInfo.result);
						try {
							JSONObject jo = new JSONObject(responseInfo.result);
							if ("0".equals(jo.optString("code"))) {
								List<HistoryOneShop> list = new HistoryOneShopParser()
										.parseJSON(responseInfo.result);
								if (list != null && list.size() != 0) {
									mSecList.clear();
									mSecList.addAll(list);
								}
								mSecAdapter.notifyDataSetChanged();
								// 先删后存
								// 抽出方法
								GlobalApplication.appDB.deleteByWhere(
										HistoryOneShop.class, null);
								SystemClock.sleep(200);
								for (HistoryOneShop pu : mSecList) {
									GlobalApplication.appDB.save(pu);
								}
							}
							oneyuan_ZR.onRefreshComplete();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						WuLog.i(TAG, "失败" + error.getExceptionCode());
						showCustomToast(error.getExceptionCode() + ";" + msg);
					}
				});
	}

	@Override
	protected void onStart() {
		super.onStart();
		mTitlePane.getLeftButton().setVisibility(View.VISIBLE);
		mTitlePane.setTitle("购买记录");
		mTitlePane.setLeftButtonTextAndListener("返回", new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void setListener() {
		mFiestLL.setOnClickListener(new MyOnClickListener(0));
		mSecLL.setOnClickListener(new MyOnClickListener(1));
		duihuan_ZR.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				getBuyHistory();
			}
		});
		duihuan_ZR.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel() {
				duihuan_ZR.onRefreshComplete();
			}
		});
		oneyuan_ZR.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				getOneBuyHistory();
			}
		});
		oneyuan_ZR.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel() {
				oneyuan_ZR.onRefreshComplete();
			}
		});
	}

	private void setData() {
		new AsyncDataLoader(new Callback() {
			@Override
			public void onStart() {
				// 查询
//				mFirstList.clear();
				try {
					List<ProductHistory> flist = GlobalApplication.appDB
							.findAll(ProductHistory.class);
					if (flist != null && flist.size() != 0) {
						mFirstList.addAll(flist);
						WuLog.i(TAG, "异步任务");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onPrepare() {
				// 处于刷新状态
				mFirstAdapter = new ProductHistoryAdapter(
						getApplicationContext(), mFirstList);
				duihuan_ZR.setAdapter(mFirstAdapter);
				duihuan_ZR.onManualRefresh();
				WuLog.i(TAG, "prepare");
			}

			@Override
			public void onFinish() {
				WuLog.i(TAG, "执行了");
				getBuyHistory();
			}
		}).execute();
	}

	private void initView() {
		mFiestLL = (LinearLayout) findViewById(R.id.buy_duihuan_list_ll);
		mSecLL = (LinearLayout) findViewById(R.id.buy_one_list_ll);
		buy_duihuan_tv = (TextView) findViewById(R.id.buy_duihuan_list);
		buy_one_tv = (TextView) findViewById(R.id.buy_one_list);
		duihuan_ZR = (ZnmRefreshListView) findViewById(R.id.duihuan_ZR);
		oneyuan_ZR = (ZnmRefreshListView) findViewById(R.id.oneyuan_history_ZR);
		// vf = (ViewFlipper) findViewById(R.id.history_vf);
	}

	/**
	 * 头标点击监听
	 */
	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		public void onClick(View v) {
			WuLog.i(TAG, "当前点击的位置" + index);
			changeTitlePane(index);

		}
	};

	private void changeTitlePane(int x) {
		switch (x) {
		case 0:
			mFiestLL.setBackgroundResource(R.drawable.fav_lefttab);
			mSecLL.setBackgroundResource(R.drawable.fav_tab_right);
			duihuan_ZR.setVisibility(View.VISIBLE);
			oneyuan_ZR.setVisibility(View.GONE);
			// vf.showNext();
			buy_duihuan_tv.setTextColor(getResources().getColor(
					R.color.tab_left));
			buy_one_tv.setTextColor(getResources().getColor(R.color.tab_right));
			break;
		case 1:
			mFiestLL.setBackgroundResource(R.drawable.fav_tab_left);
			mSecLL.setBackgroundResource(R.drawable.fav_righttab);
			duihuan_ZR.setVisibility(View.GONE);
			oneyuan_ZR.setVisibility(View.VISIBLE);
			// vf.showPrevious();
			buy_duihuan_tv.setTextColor(getResources().getColor(
					R.color.tab_right));
			buy_one_tv.setTextColor(getResources().getColor(R.color.tab_left));
			if (!mPlush) {
				new AsyncDataLoader(new Callback() {
					@Override
					public void onStart() {
						// 查询
						mSecList.clear();
						try {
							List<HistoryOneShop> list = GlobalApplication.appDB
									.findAll(HistoryOneShop.class);
							if (list != null && list.size() != 0) {
								mSecList.addAll(list);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onPrepare() {
						// 处于刷新状态
						mSecAdapter = new HistoryOneGouAdapter(
								getApplicationContext(), mSecList);
						oneyuan_ZR.setAdapter(mSecAdapter);
						oneyuan_ZR.onManualRefresh();
					}

					@Override
					public void onFinish() {
						getOneBuyHistory();
					}
				}).execute();
				mPlush = !mPlush;
			}
			break;
		}
	}

	/**
	 * 页卡切换
	 * 
	 * @author Jack 2014-3-5
	 * 
	 * 
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int arg0) {
			switch (arg0) {
			case 0:
				// 执行操作
				break;
			case 1:
				// 执行操作
				if (!mPlush) {
					new AsyncDataLoader(new Callback() {
						@Override
						public void onStart() {
							// 查询
							mSecList.clear();
							try {
								List<HistoryOneShop> list = GlobalApplication.appDB
										.findAll(HistoryOneShop.class);
								if (list != null && list.size() != 0) {
									mSecList.addAll(list);
									mSecAdapter.notifyDataSetChanged();
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}

						@Override
						public void onPrepare() {
							// 处于刷新状态
							mSecAdapter = new HistoryOneGouAdapter(
									getApplicationContext(), mSecList);
							oneyuan_ZR.setAdapter(mSecAdapter);
							oneyuan_ZR.onManualRefresh();
						}

						@Override
						public void onFinish() {
							getOneBuyHistory();
						}
					}).execute();
					mPlush = !mPlush;
				}
				break;
			default:
				break;
			}
		}

	}
}
